package com.jy.datapipeline.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url   发送请求的URL
	 * @param param 请求参数，请求参数应该是name1=value1&name2=value2的形式
	 * @return URL所代表远程资源的响应
	 * 
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlName = url + "?" + param;
			URL realUrl = new URL(urlName);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 建立实际的连接
			conn.connect();
			// 获取所有响应头字段
//			Map<String, List<String>> map = conn.getHeaderFields();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += "/n" + line;
			}
			if (StringUtils.isNotBlank(result)) {
				result = result.substring(2);
			}
		} catch (Exception e) {
			logger.error("发送GET请求出现异常！" + e);
			logger.error(e.toString(), e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error(ex.toString(), ex);
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url   发送请求的URL
	 * @param param 请求参数，请求参数应该是name1=value1&name2=value2的形式
	 * @return URL所代表远程资源的响应
	 * 
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// conn.setRequestProperty("Content-Type", "*/*;charset=UTF-8");
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*;charset=UTF-8");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("发送POST请求出现异常！" + e);
			logger.error(e.toString(), e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error(ex.toString(), ex);
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String sendPostToJson(String url, String json) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// conn.setRequestProperty("Content-Type", "*/*;charset=UTF-8");
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*;charset=UTF-8");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-type", "application/json");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(json);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("发送POST请求出现异常！" + e);
			logger.error(e.toString(), e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error(ex.toString(), ex);
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String getResponse(String serverUrl, JSONObject obj, String token) {

		// 用JAVA发起http请求，并返回json格式的结果
		String resp = null;
//		String query = obj.toString();
		//System.out.println("发送的URL的报文为:" + query);
		try {
			URL url = new URL(serverUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0");
			// con.setRequestProperty("Host", "https://fcode.coolfei.cn");
			con.setRequestProperty("DNT", "1");
			con.setRequestProperty("Connection", "keep-alive");
			con.setRequestProperty("Content-type", "application/json");
			if (token != null) {
				con.setRequestProperty("Authorization", token);
			}
			con.setRequestProperty("Referer", serverUrl);
			con.setDoInput(true);
			con.setDoOutput(true);
			OutputStream os = null;
			os = con.getOutputStream();
			os.write(obj.toString().getBytes("UTF-8"));
			os.close();
			con.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

			String line;
			StringBuffer result = new StringBuffer();
			while ((line = in.readLine()) != null) {
				line = new String(line.getBytes());
				result.append(line);
			}
			System.out.println("返回的报文:" + result.toString());
			resp = result.toString();
			con.disconnect();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resp;
	}
	
	public static String getResponse2(String serverUrl, String params) {

		// 用JAVA发起http请求，并返回json格式的结果
		String resp = null;
		//String query = obj.toString();
		//System.out.println("发送的URL的报文为:" + query);
		try {
			URL url = new URL(serverUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0");
			// con.setRequestProperty("Host", "https://fcode.coolfei.cn");
			//con.setRequestProperty("DNT", "1");
			con.setRequestProperty("Connection", "keep-alive");
			con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//			if (token != null) {
//				con.setRequestProperty("Authorization", token);
//			}
			con.setRequestProperty("Referer", serverUrl);
			con.setDoInput(true);
			con.setDoOutput(true);
			OutputStream os = null;
			os = con.getOutputStream();
			os.write(params.getBytes("UTF-8"));
			os.close();
			con.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));

			String line;
			StringBuffer result = new StringBuffer();
			while ((line = in.readLine()) != null) {
				line = new String(line.getBytes());
				result.append(line);
			}
			System.out.println("返回的报文:" + result.toString());
			resp = result.toString();
			con.disconnect();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resp;
	}

	public static String getXMLResponse(String serverUrl, String params) {

		// 用JAVA发起http请求，并返回json格式的结果
		String resp = null;
		System.out.println("发送的URL的报文为:" + params);
		try {
			URL url = new URL(serverUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
//			con.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0");
			// con.setRequestProperty("Host", "https://fcode.coolfei.cn");
//			con.setRequestProperty("DNT", "1");
//			con.setRequestProperty("Connection", "keep-alive");
			con.setRequestProperty("Content-type", "application/xml");
			con.setRequestProperty("Referer", serverUrl);
			con.setDoInput(true);
			con.setDoOutput(true);
			OutputStream os = null;
			os = con.getOutputStream();
			os.write(params.getBytes("UTF-8"));
			os.close();
			con.connect();
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

			String line;
			StringBuffer result = new StringBuffer();
			while ((line = in.readLine()) != null) {
				line = new String(line.getBytes(), "utf-8");
				result.append(line);
			}
			System.out.println("返回的报文:" + result.toString());
			resp = result.toString();
			con.disconnect();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resp;
	}

}
